package com.yizisu.basemvvm.mvvm

import android.graphics.Bitmap
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.webkit.*
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.yizisu.basemvvm.logI
import com.yizisu.basemvvm.utils.isStatusBarBlackTextColor
import com.yizisu.basemvvm.utils.navigateTo
import kotlinx.android.synthetic.main.activity_web_view_helper.*
import java.lang.ref.WeakReference


class WebViewHelperActivity : MvvmActivity() {
    companion object {
        private var it: WebViewHelperActivity? = null
        private var mUrl: String? = null
        private var mStatusBarColor: Int? = null
        private var mStatusBarTextColorIsBlack: Boolean = false
        private var mStatusBarIsTransparent: Boolean = false
        private var mTitleBar: WeakReference<View>? = null
        private var mShowTitleView: WeakReference<TextView>? = null
        fun finish() {
            it?.finish()
        }
    }

    class Builder {
        fun setUrl(url: String?): Builder {
            mUrl = url
            return this
        }

        fun setStatusBarColor(color: Int?): Builder {
            mStatusBarColor = color
            return this
        }

        fun setStatusBarTextColorIsBlack(isBlack: Boolean): Builder {
            mStatusBarTextColorIsBlack = isBlack
            return this
        }

        fun setTitleBar(view: View?): Builder {
            view ?: return this
            mTitleBar = WeakReference(view)
            return this
        }

        fun setShowTitleView(view: TextView?): Builder {
            view ?: return this
            mShowTitleView = WeakReference(view)
            return this
        }

        fun setStatusBarIsTransparent(isTransparent: Boolean): Builder {
            mStatusBarIsTransparent = isTransparent
            return this
        }

        fun start(activity: AppCompatActivity?) {
            activity ?: return
            activity.navigateTo(WebViewHelperActivity::class.java)
        }
    }

    private var isHelperPbShow = false
    override fun getLayoutResOrView(inflater: LayoutInflater): Any? =
        com.yizisu.basemvvm.R.layout.activity_web_view_helper

    override fun getClickView(): List<View?>? = listOf()

    override fun initViewModel() {
        it = this
        mStatusBarColor?.let {
            window.statusBarColor = it
        }
        isStatusBarBlackTextColor(mStatusBarTextColorIsBlack)
        mTitleBar?.get()?.let {
            helperRootView.addView(
                it, 0, LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
            )
        }
        if (mStatusBarIsTransparent) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        }
    }

    override fun initUi(savedInstanceState: Bundle?) {
        helperWebView.swipeRefreshLayout = helperLoading
        helperWebView.floatUpTopButton = helperFab
        setLoadListener()
    }

    override fun initData() {
        helperLoading.setOnRefreshListener {
            helperLoading.showLoadingView(isEnableContentView = true)
            relaod()
        }
        helperWebView.loadUrl(mUrl)
    }

    override fun onSingleClick(view: View) {
    }

    /**
     * 设置加载监听加载成功，加载失败
     */
    private fun setLoadListener() {
        helperWebView.webViewClient = object : WebViewClient() {
            private var isLoadSuccess: Boolean = true
            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                val url = request?.url?.toString()
                try {
                    if (!URLUtil.isNetworkUrl(url)) {//过滤
//                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
//                        startActivity(intent)//防止开启三方软件
                        return true
                    }
                } catch (e: Exception) {
                    return true
                }
                view?.loadUrl(url)
                return true
            }

            override fun onLoadResource(view: WebView?, url: String?) {

                if (url?.endsWith("gif") == false) {
                    logI("onLoadResource:${url}")
                    super.onLoadResource(view, url)
                }else{
                    view?.stopLoading()
                }
            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                isLoadSuccess = true
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                if (isLoadSuccess) {
                    helperLoading.showContentView()
                }
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
//                helperLoading.showOtherView()
                isLoadSuccess = false
            }
        }
        helperWebView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                if (newProgress < 100) {
                    if (!isHelperPbShow) {
                        isHelperPbShow = true
                        helperPb.show()
                    }
                    helperPb.progress = newProgress
                } else {
                    if (isHelperPbShow) {
                        isHelperPbShow = false
                        helperPb.hide()
                    }
                }
            }

            override fun onJsBeforeUnload(
                view: WebView?,
                url: String?,
                message: String?,
                result: JsResult?
            ): Boolean {
                return super.onJsBeforeUnload(view, url, message, result)
            }

            override fun getDefaultVideoPoster(): Bitmap? {
                return super.getDefaultVideoPoster()
            }

            override fun getVideoLoadingProgressView(): View? {
                return super.getVideoLoadingProgressView()
            }

            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
                mShowTitleView?.get()?.text = title
            }
        }

    }

    override fun onDestroy() {
        it = null
        super.onDestroy()
        mTitleBar?.clear()
        mTitleBar = null
        mShowTitleView?.clear()
        mShowTitleView = null
    }

    private fun relaod() {
        helperWebView.reload()
    }

    override fun onBackPressed() {
        if (helperWebView.canGoBack()) {
            helperWebView.goBack()
        } else {
            super.onBackPressed()
        }
    }
}
